<template>
  <div class="h-screen flex flex-col bg-zinc-950 text-gray-100 font-sans antialiased">

    <!-- 顶部导航栏 -->
    <header :class="[
      'fixed top-8 left-0 w-full z-30 backdrop-blur-3xl border-b shadow-md transition-all duration-500 ease-in-out py-2 flex flex-col gap-2',
      isDark ? 'bg-gray-900/50 border-gray-700/50' : 'bg-white/70 border-gray-300/50'
    ]">


      <!-- 目录切换和搜索框 -->
      <div class="grid grid-cols-3 items-center px-6 py-1 mt-1">
        <div class="flex items-center gap-2 overflow-x-auto custom-scrollbar-horizontal pr-4">
          <div v-for="(dir, index) in directories" :key="dir" class="relative group">
            <!-- 目录按钮 -->
            <button @click="switchDirectory(index)" :class="[
              'px-3 cursor-pointer py-1.5 rounded-full text-sm font-medium whitespace-nowrap transition-colors duration-200',
              activeDirIndex === index
                ? 'bg-blue-600 text-white shadow-md'
                : isDark
                  ? 'bg-gray-800/70 text-gray-300 hover:bg-gray-700/70'
                  : 'bg-gray-200 text-gray-800 hover:bg-gray-300'
            ]">
              {{ dir.split('/').pop() || dir }}
            </button>

            <!-- 删除按钮（悬浮显示） -->
            <button @click.stop="deleteDirectory(index)"
              class="absolute cursor-pointer top-1/2 -translate-y-1/2 right-2  w-5 h-5 rounded-full bg-red-500 text-white text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200"
              >
              ×
            </button>
          </div>

          <!-- 添加目录按钮 -->
          <button @click="chooseDirectory" :class="[
            'px-3 cursor-pointer py-1 rounded-full',
            isDark ? 'bg-gray-800/70 text-gray-300 hover:bg-gray-700/70' : 'bg-gray-200 text-gray-800 hover:bg-gray-300'
          ]">
            +
          </button>
        </div>

        <div class="col-start-2 justify-self-center relative w-64">
          <svg xmlns="http://www.w3.org/2000/svg"
            :class="['w-5 h-5 absolute left-3 top-1/2 -translate-y-1/2', isDark ? 'text-gray-500' : 'text-gray-400']"
            viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
            stroke-linejoin="round">
            <circle cx="11" cy="11" r="8"></circle>
            <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
          </svg>
          <input ref="searchInput" v-model="searchQuery" type="text" :class="[
            'w-full border rounded-full pl-10 pr-4 py-2 text-sm focus:outline-none focus:ring-2 placeholder-gray-400',
            isDark
              ? 'bg-gray-800/70 border-gray-700/50 text-gray-200 focus:ring-blue-500'
              : 'bg-gray-100 border-gray-300 text-gray-900 focus:ring-blue-400'
          ]" placeholder="搜索电影" />
        </div>


        <!-- 工具按钮 -->
        <div class="flex items-center justify-self-end gap-4">
          <!-- 刷新按钮，上方显示 tooltip -->
          <Tooltip text="刷新电影列表" position="bottom">
            <button @click="refreshMovies"
              class="p-2 cursor-pointer rounded-full hover:bg-gray-700/50 transition-colors">
              <img src="/src/assets/svg/reflash.svg" alt="刷新" class="w-6 h-6 transition-colors duration-300"
                :class="!isDark ? 'invert-0' : 'invert'" />
            </button>
          </Tooltip>

          <!-- 处理字幕按钮，上方显示 tooltip -->
          <Tooltip text="处理字幕" position="bottom">
            <button @click="runSubtitleProcess"
              class="p-2 cursor-pointer rounded-full hover:bg-gray-700/50 transition-colors">
              <img src="/src/assets/svg/subtitles.svg" alt="字幕" class="w-6 h-6 transition-colors duration-300"
                :class="!isDark ? 'invert-0' : 'invert'" />
            </button>
          </Tooltip>

          <!-- 一键获取按钮，上方显示 tooltip -->
          <Tooltip text="一键获取空缺的TMDB电影信息" position="bottom">
            <button @click="fetchAllMovies" :disabled="movies.length === 0 || downloadingAll"
              class="flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-full transition-all duration-300 active:scale-95 shadow-lg"
              :class="isDark
                ? 'bg-blue-600 text-white disabled:bg-gray-700 disabled:cursor-not-allowed'
                : 'bg-blue-500 text-white disabled:bg-gray-300 disabled:text-gray-500'">
              <template v-if="downloadingAll">
                <img src="/src/assets/svg/loading.svg" class="h-5 w-5 transition-colors duration-300"
                  :class="isDark ? 'filter invert-50' : 'filter invert-0'"
                  style="animation: spin 2.5s linear infinite;" />
                <span>获取中 {{ downloadProgress.current }}/{{ downloadProgress.total }}</span>
              </template>
              <template v-else>
                <img src="/src/assets/svg/download.svg" alt="一键获取信息" class="w-5 h-5 text-white" />
                <span>一键获取</span>
              </template>
            </button>
          </Tooltip>

          <!-- 切换暗/亮模式按钮，上方显示 tooltip -->
          <Tooltip :text="isDark ? '切换日间模式' : '切换夜间模式'" position="bottom">
            <button @click="toggleDarkMode"
              class="p-2 cursor-pointer rounded-full hover:bg-gray-700/50 transition-colors">
              <img v-if="isDark" src="/src/assets/svg/sun.svg" alt="切换日间模式" class="w-6 h-6" />
              <img v-else src="/src/assets/svg/moon.svg" alt="切换夜间模式" class="w-6 h-6" />
            </button>
          </Tooltip>
        </div>
      </div>
    </header>

    <!-- 主要内容区域 -->
    <main ref="scroller"
      class="flex-1 min-h-0 p-8 overflow-y-auto custom-scrollbar pt-24 pb-24 transition-colors duration-500"
      :class="isDark ? 'bg-zinc-950' : 'bg-gray-100'">

      <div v-if="loadingMovies" class="flex flex-col justify-center items-center h-full">
        <img src="/src/assets/svg/loading.svg" class="h-12 w-12 transition-colors duration-300"
          :class="isDark ? 'filter invert-50' : 'filter invert-0'" style="animation: spin 2.5s linear infinite;" />
        <span :class="isDark ? 'text-gray-400' : 'text-gray-600'" class="mt-4 text-lg">加载中...</span>
      </div>

      <div v-else-if="filteredMovies.length === 0" :class="isDark ? 'text-gray-500' : 'text-gray-700'"
        class="text-center mt-20 text-lg">
        {{ movies.length > 0 ? '未找到相关电影' : '暂无电影，请先选择目录' }}
      </div>

      <TransitionGroup v-else name="movie-list" tag="ul"
        class="grid gap-8 grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7">
        <li v-for="movie in filteredMovies" :key="movie.name" @click="goToDetail(movie)"
          @contextmenu.prevent="openEditModal(movie)" :class="[
            'cursor-pointer rounded-2xl overflow-hidden shadow-md hover:shadow-lg transition-all duration-300 transform hover:scale-105 relative',
            isDark
              ? 'bg-gray-800/60 text-gray-200 shadow-black/40'
              : 'bg-white/80 text-gray-900 shadow-gray-300/50'
          ]">

          <div :class="[
            'w-full pb-[150%] relative flex items-center justify-center rounded-t-xl overflow-hidden',
            isDark ? 'bg-gray-700/60' : 'bg-gray-200/80'
          ]">
            <img v-if="movie.cover" :src="movie.cover"
              class="absolute top-0 left-0 w-full h-full object-cover rounded-t-xl" />
            <span v-else :class="isDark ? 'text-gray-500' : 'text-gray-400'"
              class="absolute text-5xl opacity-50 pt-[150%]">🎬</span>
          </div>

          <div :class="isDark ? 'text-gray-200' : 'text-gray-900'"
            class="py-2 px-3 text-center text-sm font-medium truncate leading-tight">
            {{ movie.name }}
          </div>
        </li>
      </TransitionGroup>
    </main>


    <!-- 搜索模态框 -->
    <div v-if="showModal" class="fixed inset-0 bg-black/70 flex items-center justify-center z-50 animate-fade-in"
      @click.self="showModal = false">
      <div :class="[
        'backdrop-blur-3xl rounded-3xl shadow-2xl w-full max-w-2xl max-h-[80vh] flex flex-col overflow-hidden transform scale-95 animate-zoom-in',
        isDark ? 'bg-gray-800/80 text-gray-100' : 'bg-white/95 text-gray-900'
      ]">
        <div class="p-6 border-b flex flex-col gap-3 sticky top-0 z-20"
          :class="isDark ? 'border-gray-700/50 bg-gray-800/80' : 'border-gray-200 bg-white/80'">
          <h2 class="text-2xl font-bold text-blue-500">电影信息搜索</h2>
          <div class="relative">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 absolute left-3 top-1/2 -translate-y-1/2"
              :class="isDark ? 'text-gray-500' : 'text-gray-400'" viewBox="0 0 24 24" fill="none" stroke="currentColor"
              stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <circle cx="11" cy="11" r="8"></circle>
              <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
            </svg>
            <input v-model="currentMovieName" @keyup.enter="searchMoviesInfo" type="text" :class="[
              'w-full border rounded-full pl-10 pr-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500',
              isDark
                ? 'bg-gray-700/70 border-gray-600/50 text-gray-200 placeholder-gray-400'
                : 'bg-gray-100 border-gray-300 text-gray-900 placeholder-gray-500'
            ]" placeholder="输入电影名搜索" />
          </div>
        </div>
        <div class="p-4 flex-1 overflow-y-auto">
          <div v-if="loadingMovie" class="flex justify-center items-center h-full min-h-[200px]">
            <img src="/src/assets/svg/loading.svg" class="h-10 w-10 transition-colors duration-300"
              :class="isDark ? 'filter invert-50' : 'filter invert-0'" style="animation: spin 2.5s linear infinite;" />
          </div>
          <p v-else-if="searchResults.length === 0" :class="isDark ? 'text-gray-500' : 'text-gray-600'"
            class="text-center mt-10">暂无搜索结果</p>
          <div v-else class="grid grid-cols-2 md:grid-cols-3 gap-6">
            <div v-for="movie in searchResults" :key="movie.id" @click="fetchMovieDetails(movie)"
              class="flex flex-col items-center cursor-pointer hover:scale-105 transition-transform duration-200">
              <div :class="[
                'w-full pb-[150%] relative flex items-center justify-center rounded-xl overflow-hidden',
                isDark ? 'bg-gray-700' : 'bg-gray-200'
              ]">
                <img v-if="movie.localPoster" :src="movie.localPoster"
                  class="absolute top-0 left-0 w-full h-full object-cover rounded-xl" alt="poster" />
                <span v-else :class="isDark ? 'text-gray-500' : 'text-gray-400'"
                  class="absolute text-5xl opacity-50">🎬</span>
              </div>
              <div class="mt-3 text-center text-sm font-medium truncate w-full"
                :class="isDark ? 'text-gray-300' : 'text-gray-800'">
                {{ movie.title }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 下载遮罩 -->
    <div v-if="downloading" class="fixed inset-0 z-[9999] bg-black/80 flex items-center justify-center animate-fade-in">
      <div :class="[
        'backdrop-blur-xl p-8 rounded-3xl flex flex-col items-center gap-4 shadow-2xl',
        isDark ? 'bg-gray-800/80' : 'bg-white/90'
      ]">
        <img src="/src/assets/svg/loading.svg" class="h-10 w-10 transition-colors duration-300"
          :class="isDark ? 'filter invert-50' : 'filter invert-0'" style="animation: spin 2.5s linear infinite;" />
        <span :class="isDark ? 'text-gray-300' : 'text-gray-800'" class="font-medium text-lg">下载中，请稍候...</span>
      </div>
    </div>

    <!-- Toast -->
    <div v-if="showToast" :class="[
      'fixed bottom-6 right-6 px-5 py-3 rounded-xl shadow-lg z-50 transition-all duration-300 transform animate-slide-in-right',
      isDark ? 'bg-gray-700/70 text-white' : 'bg-gray-200 text-gray-800'
    ]">
      {{ toastMessage }}
    </div>
  </div>
</template>


<script lang="ts" setup>
import { ref, onMounted, computed, watch, onActivated, nextTick, onDeactivated, onBeforeUnmount } from 'vue';
import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router';
import Tooltip from '../components/Tooltip.vue'
import { filterMoviesByPinyin } from '../payload/searchPayload';

const router = useRouter();

// 多目录状态
const directories = ref<string[]>([]);    // 保存所有目录
const activeDirIndex = ref<number>(0);    // 当前激活目录索引
const movieDir = computed(() => directories.value[activeDirIndex.value] || '');


// 运行字幕处理
const runSubtitleProcess = async () => {
  if (!movieDir.value) {
    showDownloadToast('当前目录不存在');
    return;
  }

  try {
    const result = await (window as any).electronAPI.runSubtitleBat(movieDir.value);
    showDownloadToast(result);
  } catch (err: any) {
    showDownloadToast(`运行失败: ${err}`);
  }
};

// 当前目录的电影列表
const movies = ref<{ name: string; path: string; cover?: string; backdrop?: string; details?: any }[]>([]);

// 搜索与过滤
const searchQuery = ref('');
const filteredMovies = computed(() =>
  filterMoviesByPinyin({ items: movies.value, query: searchQuery.value })
);
// 列数设置
const columnsPerRow = ref<number>(4);
const setColumns = (num: number) => {
  columnsPerRow.value = num;
  localStorage.setItem('columnsPerRow', num.toString());
};


/**
 * 网格布局样式
 * @returns {Object} 网格布局样式对象
 */
const gridStyle = computed(() => ({
  display: 'grid',
  gridTemplateColumns: `repeat(${columnsPerRow.value}, minmax(0, 1fr))`,
  gap: '1.5rem',
  transition: 'grid-template-columns 0.5s ease'
}));

// Toast
const toastMessage = ref('');
const showToast = ref(false);
const showDownloadToast = (msg: string) => {
  toastMessage.value = msg;
  showToast.value = true;
  setTimeout(() => {
    showToast.value = false;
    toastMessage.value = '';
  }, 3000);
};

// 下载状态
const downloadingAll = ref(false);
const downloadProgress = ref({ current: 0, total: 0 });
const downloading = ref(false);

// 电影搜索模态
const showModal = ref(false);
const currentMovieName = ref('');
let selectedMovieName = ref('');
const searchResults = ref<any[]>([]);
const loadingMovie = ref(false);

// 打开电影搜索模态
const openEditModal = (movie: any) => {
  currentMovieName.value = movie.name;
  selectedMovieName.value = movie.name;
  showModal.value = true;
  searchMoviesInfo();
};

// 保存当前目录列表和激活索引到 localStorage
const persistDirs = () => {
  localStorage.setItem('directories', JSON.stringify(directories.value || []));
  localStorage.setItem('activeDirIndex', String(activeDirIndex.value ?? 0));

  // 同步更新 movieDir
  const dir = directories.value[activeDirIndex.value];
  if (dir) localStorage.setItem('movieDir', dir);
};
const loadingMovies = ref(false);
// 选择目录（新增）
const chooseDirectory = async () => {
  const api = (window as any).electronAPI;
  if (!api) return;

  const path = await api.selectDirectory();
  if (path) {
    // 如果已经存在则切换到该目录
    const idx = directories.value.indexOf(path);
    if (idx >= 0) {
      activeDirIndex.value = idx;
    } else {
      directories.value.push(path);
      activeDirIndex.value = directories.value.length - 1;
    }

    // 持久化并更新 movieDir
    persistDirs();

    // 更新 movieDir 下的电影列表
    const dir = directories.value[activeDirIndex.value];
    if (dir) {
      loadingMovies.value = true;
      try {
        movies.value = await api.getMovieList(dir);
      } finally {
        loadingMovies.value = false;
      }
    }
  }
};

// 切换目录（标签点击）
const switchDirectory = async (index: number) => {
  if (index === activeDirIndex.value) return;
  activeDirIndex.value = index;

  // 持久化被选中的索引，同时更新 movieDir
  persistDirs();

  const api = (window as any).electronAPI;
  if (!api) return;
  const dir = directories.value[activeDirIndex.value];
  loadingMovies.value = true;
  try {
    movies.value = dir ? await api.getMovieList(dir) : [];
  } finally {
    loadingMovies.value = false;
  }
};
// 加载缓存目录
const loadDirectoriesFromCache = async () => {
  const api = (window as any).electronAPI;
  if (!api) return;
  const cachedDirs = localStorage.getItem('directories');
  if (cachedDirs) {
    try {
      const arr = JSON.parse(cachedDirs) as string[];
      directories.value = Array.isArray(arr) ? arr : [];
    } catch {
      directories.value = [];
    }
  }

  const cachedIndex = localStorage.getItem('activeDirIndex');
  if (typeof cachedIndex === 'string') {
    const idx = parseInt(cachedIndex);
    if (!Number.isNaN(idx)) activeDirIndex.value = idx;
  }

  // 容错：如果 activeIndex 超出范围，回到 0
  if (activeDirIndex.value < 0 || activeDirIndex.value >= directories.value.length) {
    activeDirIndex.value = 0;
  }

  // 恢复 movieDir
  const dir = directories.value[activeDirIndex.value];
  if (dir) localStorage.setItem('movieDir', dir);

  // 加载当前激活目录的电影
  if (api && directories.value.length > 0) {
    if (dir) {
      loadingMovies.value = true;
      try {
        movies.value = await api.getMovieList(dir);
      } finally {
        loadingMovies.value = false;
      }
    }
  }
};


// 跳转电影详情
const goToDetail = (movie: any) => {
  // 保存当前目录到localStorage
  localStorage.setItem('movieDir', movieDir.value);
  router.push({ name: 'movieDetail', params: { name: movie.name } })
};
// 搜索电影信息
const searchMoviesInfo = async () => {
  if (loadingMovie.value) return;
  loadingMovie.value = true;
  try {
    const api = (window as any).electronAPI;
    const results = await api.searchMovies(currentMovieName.value);
    for (const movie of results) {
      if (movie.poster_path) {
        try {
          const localPath = await api.downloadImageBase64(
            `https://image.tmdb.org/t/p/w200${movie.poster_path}`
          );
          movie.localPoster = localPath;
        } catch {
          movie.localPoster = '';
        }
      } else {
        movie.localPoster = '';
      }
    }
    searchResults.value = results;
  } finally {
    loadingMovie.value = false;
  }
};

// 保存电影详情
const fetchMovieDetails = async (movie: any) => {
  if (!movieDir.value) return;
  downloading.value = true;
  showModal.value = false;

  const moviePath = `${movieDir.value}/${selectedMovieName.value}`;
  const api = (window as any).electronAPI;
  const result = await api.saveMovieDetails(movie.id, moviePath);

  if (!result.success) {
    console.error('保存电影失败:', result.error);
    showDownloadToast('保存电影失败');
  } else {
    showDownloadToast('保存电影成功');
  }
  loadingMovies.value = true;
  try {
    movies.value = await api.getMovieList(movieDir.value);
  } finally {
    loadingMovies.value = false;
  }
  downloading.value = false;
};

// 一键获取所有电影信息
const fetchAllMovies = async () => {
  if (!movieDir.value || movies.value.length === 0) return;
  downloadingAll.value = true;
  downloadProgress.value = { current: 0, total: movies.value.length };
  const api = (window as any).electronAPI;

  for (let i = 0; i < movies.value.length; i++) {
    const movie = movies.value[i];
    if (movie.cover && movie.backdrop && movie.details) {
      downloadProgress.value.current = i + 1;
      continue;
    }
    try {
      let movieId = '';
      const searchRes = await api.searchMovies(movie.name);
      if (Array.isArray(searchRes) && searchRes.length > 0) {
        movieId = searchRes[0].id;
      }
      if (movieId) {
        const moviePath = `${movieDir.value}/${movie.name}`;
        await api.saveMovieDetails(movieId, moviePath);
      }
    } catch (err) {
      console.error('获取电影信息失败:', movie.name, err);
    }
    downloadProgress.value.current = i + 1;
  }
  loadingMovies.value = true;
  try {
    movies.value = await api.getMovieList(movieDir.value);
  } finally {
    loadingMovies.value = false;
  }
  downloadingAll.value = false;
  showDownloadToast('所有电影信息获取完成！');
};


// 刷新目录电影
const refreshMovies = async () => {
  const api = (window as any).electronAPI;
  if (!movieDir.value) return;
  loadingMovies.value = true;
  try {
    movies.value = await api.getMovieList(movieDir.value);
  } finally {
    loadingMovies.value = false;
  }
}
const deleteDirectory = async (index: number) => {
  // 从directories数组中移除指定索引的目录
  directories.value.splice(index, 1);

  // 如果删除的是当前激活的目录或者激活索引超出范围
  if (index === activeDirIndex.value || activeDirIndex.value >= directories.value.length) {
    // 如果还有剩余目录，激活第一个目录，否则设为-1
    activeDirIndex.value = directories.value.length > 0 ? 0 : -1;
  } else if (index < activeDirIndex.value) {
    // 如果删除的目录在当前激活目录之前，需要将激活索引减1
    activeDirIndex.value--;
  }

  // 持久化更新后的目录列表和激活索引
  persistDirs();

  const api = (window as any).electronAPI;
  if (!api) return;

  // 如果还有目录，加载新激活目录的电影列表
  if (directories.value.length > 0 && activeDirIndex.value >= 0) {
    const dir = directories.value[activeDirIndex.value];
    if (dir) {
      loadingMovies.value = true;
      try {
        movies.value = await api.getMovieList(dir);
      } finally {
        loadingMovies.value = false;
      }
    }
  } else {
    // 如果没有目录了，清空电影列表
    movies.value = [];
  }
}
const isDark = ref(true)
const toggleDarkMode = () => {
  isDark.value = !isDark.value
  const root = document.documentElement
  if (isDark.value) {
    root.classList.add('dark')
    localStorage.setItem('theme', 'dark')
  } else {
    root.classList.remove('dark')
    localStorage.setItem('theme', 'light')
  }
}


// 滚动缓存
const scrollPositions = new Map<string, number>()
const route = useRoute()
const scroller = ref<HTMLElement | null>(null)
const key = () => `scroll:${route.fullPath}`

// 保存滚动位置
function saveScroll() {
  if (scroller.value) {
    scrollPositions.set(key(), scroller.value.scrollTop)
    console.log('保存滚动位置', scroller.value.scrollTop)
  }
}

// 恢复滚动位置
async function restoreScroll() {
  await nextTick() // 等 Vue 渲染 DOM
  await nextTick() // 再等异步列表渲染完成
  if (scroller.value) {
    const pos = scrollPositions.get(key()) ?? 0
    scroller.value.scrollTop = pos
  }
}


// 搜索输入框ref
const searchInput = ref<HTMLInputElement | null>(null);
// 搜索输入框聚焦

function handleKeydown(e: KeyboardEvent) {
  // Ctrl+F 或 Cmd+F
  if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'f') {
    e.preventDefault(); // 阻止浏览器默认搜索

    const input = searchInput.value;
    if (!input) return;

    // 如果当前已经聚焦，则取消聚焦
    if (document.activeElement === input) {
      input.blur();
    } else {
      input.focus();
    }
  }

  // Esc 取消聚焦
  if (e.key === 'Escape') {
    searchInput.value?.blur();
  }
}

// 页面加载：恢复主题、列数、目录、激活索引、加载电影
onMounted(async () => {
  window.addEventListener('keydown', handleKeydown);
  // 主题
  const savedTheme = localStorage.getItem('theme')
  if (savedTheme === 'light') {
    isDark.value = false
    document.documentElement.classList.remove('dark')
  } else {
    isDark.value = true
    document.documentElement.classList.add('dark')
  }

  // 列数
  const savedCols = localStorage.getItem('columnsPerRow')
  if (savedCols) columnsPerRow.value = parseInt(savedCols)

  // 恢复目录列表和激活索引
  const cachedDirs = localStorage.getItem('directories')
  const cachedIndex = localStorage.getItem('activeDirIndex')
  if (cachedDirs) {
    try {
      const arr = JSON.parse(cachedDirs) as string[]
      directories.value = Array.isArray(arr) ? arr : []
    } catch {
      directories.value = []
    }
  }
  if (typeof cachedIndex === 'string') {
    const idx = parseInt(cachedIndex)
    if (!Number.isNaN(idx)) activeDirIndex.value = idx
  }

  // 容错
  if (activeDirIndex.value < 0 || activeDirIndex.value >= directories.value.length) {
    activeDirIndex.value = 0
  }

  // 保存 movieDir
  const dir = directories.value[activeDirIndex.value]
  if (dir) localStorage.setItem('movieDir', dir)

  // 加载电影
  const api = (window as any).electronAPI
  if (api && directories.value.length > 0 && dir) {
    loadingMovies.value = true
    try {
      movies.value = await api.getMovieList(dir)
    } finally {
      loadingMovies.value = false
    }
  }
  if (scroller.value) {
    scroller.value.addEventListener('scroll', () => {
      scrollPositions.set(key(), scroller.value!.scrollTop)
    })
  }
})
onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleKeydown);
});
// keep-alive 生命周期
onActivated(() => {
  restoreScroll()
})
onDeactivated(() => {
  saveScroll()
})

</script>

<script lang="ts">
export default {
  name: 'MovieList'
}
</script>
<style lang="css">
/* 列表项进入/离开动画 */
.movie-list-move,
.movie-list-enter-active,
.movie-list-leave-active {
  /* 只对透明度和缩放过渡，0.4秒，缓动自然 */
  transition: opacity 0.4s cubic-bezier(0.4, 0, 0.2, 1),
    transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 初始状态：透明且缩小 */
.movie-list-enter-from,
.movie-list-leave-to {
  opacity: 0;
  transform: scale(0.8);
  transform-origin: top center;
  /* 缩放从顶部开始，更自然 */
}

/* 离开动画时占位，避免布局跳动 */
.movie-list-leave-active {
  position: absolute;
}

/* 自定义滚动条样式 */
.custom-scrollbar::-webkit-scrollbar {
  width: 8px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: transparent;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background-color: #4a4a4a;
  border-radius: 4px;
  border: 2px solid transparent;
  background-clip: padding-box;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background-color: #666;
}

.custom-scrollbar {
  scrollbar-width: thin;
  scrollbar-color: #4a4a4a transparent;
}
</style>
